<?php
#################################
# Metadata Enhancement for Repositories (MER) 
# This software is an overlay repository search interface that uses a 
# text mined index of terms.
# Copyright (C) 2011  Rory McNicholl (University of London Computer Centre), Robert Drinkall (University College London)

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Contact repositories@ulcc.ac.uk

##################################

# In order to use MER's term harvesting functionality you will need access to the TerMine web service
# http://www.nactem.ac.uk/software/termine/webservice/

include "../mer.php";

$mer = new MER();

$TerMine_wsdl = $mer->config->termine;

$cli = (php_sapi_name() != 'cli')? false : true; 
#If we're on the cli lets just test the TerMine web service and go home....
if($cli){
	try {
		$T_client = new SoapClient($TerMine_wsdl);
		$termine_output = $T_client->analyze("The quick brown fox jumped over the lazy imagination.");
	} catch (SoapFault $fault) {
		#print something here? or maybe we are listening fo silence...
		exit;
	}
	print "OK\n";
	exit;
}

if(isset($_REQUEST["file"])){
	$file = $_REQUEST["file"];
}else{
	die("need a file to process");
}
if(isset($_REQUEST["r_id"])){
	$record_id = $_REQUEST["r_id"];
}else{
	die("need a record_id to associate terms with");
}

$T_client = new SoapClient($TerMine_wsdl);

$split_text = split_text($file,$split_file);
if(!$split_text){
	$termine_output = "<error>Sentence spliter has failed</error>\n";
}else{
	$termine_output = $T_client->analyze($split_text, "", "xml","|","");

	if (is_soap_fault($termine_output)) {
	    trigger_error("SOAP Fault: (faultcode: {$termine_output->faultcode}, faultstring: {$termine_output->faultstring})", E_USER_ERROR);
	}

}
header('Content-Type: text/xml');
print $termine_output;
exit;

//splits a text file into sentences and returns an string in which sentence are delimited by newlines.
function split_text($text_file,&$split_file){
	//Need to put the sentence splitter somewhere better
	$out = array();
	$cmd ="cat ".$text_file." | java -jar ./sptoolkit.jar -f 2"; 
	#print $cmd."\n";
	exec($cmd,$out,$ret);
	if($ret)
		return false;
	$text_str = join("\n",$out);

	return $text_str;
}

